package com.demo.common;

import com.demo.user.Resources;
import com.demo.user.User;
import com.demo.user.UserValidator;
import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.core.Controller;

/**
 * CommonController
 */
public class CommonController extends Controller {

	@ClearInterceptor(ClearLayer.ALL)
	public void index() {
		render("/common/index.jsp");
	}

	@ClearInterceptor(ClearLayer.ALL)
	@Before(UserValidator.class)
	public void login() {
		String loginUserName = getPara("loginUserName");
		String loginPassword = getPara("loginPassword");
		User loginUser = User.getUser(loginUserName, loginPassword);
		if (loginUser == null) {
			setAttr("loginError", "用户名或密码错误");
			render("login.jsp");
		} else {
			getSession().setAttribute("loginUser", loginUser);
			redirect("/blog");
		}
	}

	public void loginOut() {
		getSession().removeAttribute("loginUser");
		Resources.antuMap.clear();
		Resources.userActionKeyList.clear();
		render("login.jsp");
	}

	public void updatePassword() {
		if (getSessionAttr("loginUser") != null)
			render("updatepassword.jsp");
		else
			render("login.jsp");
	}

	public void savePassword() {
		String oldPassword = getPara("oldPassword");
		String newPassword = getPara("newPassword");
		if (getSessionAttr("loginUser") == null)
			render("login.jsp");
		else {
			User loginUser = (User) getSessionAttr("loginUser");
			if (loginUser.getStr("password").equals(oldPassword)) {
				loginUser.set("password", newPassword).update();
				render("updatepwd-success.jsp");
			} else {
				setAttr("passwordMsg", "原密码错误");
				render("updatepassword.jsp");
			}

		}
	}
}
